package com.example.greenshuttle.fragment;

import java.util.ArrayList;
import java.util.List;

import com.example.greenshuttle.MapDiscriptionActivity;
import com.example.greenshuttle.R;
import com.example.greenshuttle.data.HomeListItemMsg;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnLastItemVisibleListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import android.support.v4.app.Fragment;
import android.text.format.DateUtils;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;


public class HomeFragment extends Fragment {

	private View mView;
	
	/**
	 * listView中的数据集合
	 */
	private List<HomeListItemMsg> mData;
	private PullToRefreshListView mPullRefreshListView;
	private mBaseAdapter mAdapter;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View contactsLayout = inflater.inflate(R.layout.main_tab_home,
				container, false);
		mView = contactsLayout;
				
		initListView();
		
		return contactsLayout;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		

	}

	/**
	 * 开源库pulltorefresh，下拉刷新listview的初始化操作
	 */
	private void initListView() {
		mPullRefreshListView = (PullToRefreshListView) mView
				.findViewById(R.id.main_pull_refresh_list);

		// Set a listener to be invoked when the list should be refreshed.
		mPullRefreshListView
				.setOnRefreshListener(new OnRefreshListener<ListView>() {

					@Override
					public void onRefresh(
							PullToRefreshBase<ListView> refreshView) {
						String label = DateUtils.formatDateTime(getActivity()
								.getApplicationContext(), System
								.currentTimeMillis(),
								DateUtils.FORMAT_SHOW_TIME
										| DateUtils.FORMAT_SHOW_DATE
										| DateUtils.FORMAT_ABBREV_ALL);

						// Update the LastUpdatedLabel
						refreshView.getLoadingLayoutProxy()
								.setLastUpdatedLabel(label);

						// Do work to refresh the list here.
						new GetDataTask().execute();
					}
				});

		// Add an end-of-list listener
		mPullRefreshListView
				.setOnLastItemVisibleListener(new OnLastItemVisibleListener() {

					@Override
					public void onLastItemVisible() {
						Toast.makeText(getActivity().getApplicationContext(), "End of List!",
								Toast.LENGTH_SHORT).show();
					}
				});

		/*
		 * add click listener
		 * by ch
		 */
		mPullRefreshListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position,
					long id ) {
				//position代表listview中的第几个item，从1开始
				int pos = position - 1;
				String time = mData.get(pos).getsTime();
				String num = mData.get(pos).getsNum();
				String startplace = mData.get(pos).getsStartPlace();
				String endplace = mData.get(pos).getsEndPlace();
				Double slat = mData.get(pos).getSlat();
				Double slng = mData.get(pos).getSlng();
				Double elat = mData.get(pos).getElat();
				Double elng = mData.get(pos).getElng();
				
				Toast.makeText(getActivity().getApplicationContext(), "position="+position+",time:"+time+",num:"+num+",startplace:"+startplace+",endplace:"+endplace, Toast.LENGTH_LONG).show();
				
				try {
					Thread.sleep(500);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				//创建意图，打开activity
				Intent intent = new Intent(getActivity(), MapDiscriptionActivity.class);
				//使用bundle传递数据
				Bundle bundle = new Bundle();
				bundle.putString("time", time);
				bundle.putString("num", num);
				bundle.putString("startplace", startplace);
				bundle.putString("endplace", endplace);
				bundle.putDouble("slat", slat);
				bundle.putDouble("slng", slng);
				bundle.putDouble("elat", elat);
				bundle.putDouble("elng", elng);
				intent.putExtras(bundle);
				startActivity(intent);
			}
		});
		
		ListView actualListView = mPullRefreshListView.getRefreshableView();

		// Need to use the Actual ListView when registering for Context Menu
		registerForContextMenu(actualListView);

		mData = getData();

//		mAdapter = new ArrayAdapter<String>(getActivity(), R.layout.main_tab_home_listview_item, mListItems);

		mAdapter = new mBaseAdapter(getActivity().getApplicationContext());
//		mAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, mListItems);
//		/**
//		 * Add Sound Event Listener
//		 */
//		SoundPullEventListener<ListView> soundListener = new SoundPullEventListener<ListView>(
//				this);
//		// 声音
//		soundListener.addSoundEvent(State.PULL_TO_REFRESH, R.raw.pull_event);
//		soundListener.addSoundEvent(State.RESET, R.raw.reset_sound);
//		soundListener.addSoundEvent(State.REFRESHING, R.raw.refreshing_sound);
//		mPullRefreshListView.setOnPullEventListener(soundListener);

		// You can also just use setListAdapter(mAdapter) or
		// mPullRefreshListView.setAdapter(mAdapter)
		actualListView.setAdapter(mAdapter);
	}

	/**
	 * 开源库pulltorefresh，下拉刷新listview的依赖函数
	 */
	private class GetDataTask extends AsyncTask<Void, Void, List<HomeListItemMsg> > {

		@Override
		protected void onPostExecute(List<HomeListItemMsg> result) {
//			mListItems.addFirst("Added after refresh...");
			mAdapter.notifyDataSetChanged();

			// Call onRefreshComplete when the list has been refreshed.
			mPullRefreshListView.onRefreshComplete();

			super.onPostExecute(result);
		}

		@Override
		protected List<HomeListItemMsg> doInBackground(Void... params) {
			try {
				Thread.sleep(4000);
			} catch (InterruptedException e) {
			}
			return mData;
		}

	}

//	@Override
//	public void onCreateContextMenu(ContextMenu menu, View v,
//			ContextMenuInfo menuInfo) {
//		AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
//
//		menu.setHeaderTitle("Item: "
//				+ ((AdapterView<ListAdapter>) mView.findViewById(
//						R.id.main_pull_refresh_list))
//						.getItemAtPosition(info.position));
//		menu.add("Item 1");
//		menu.add("Item 2");
//		menu.add("Item 3");
//		menu.add("Item 4");
//		super.onCreateContextMenu(menu, v, menuInfo);
//	}

	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		// TODO Auto-generated method stub
		
		Toast.makeText(getActivity().getApplicationContext(), "ttt", Toast.LENGTH_SHORT).show();
		
		
		super.onCreateContextMenu(menu, v, menuInfo);
	}

	/**
	 * listview对应每行item的结构
	 */
	private class ViewHolder {
		public TextView time;
		public TextView num_of_people;
		public TextView startplace;
		public TextView endplace;
	}
	
//	/**
//	 * listView中的数据集合
//	 */
//	private List<HomeListItemMsg> mData = new ArrayList<HomeListItemMsg>();
	
	/**
	 * 获取data数据，可由json传递来
	 */
	public List<HomeListItemMsg> getData() {
		List<HomeListItemMsg> mdata = new ArrayList<HomeListItemMsg>();
		HomeListItemMsg i1 = new HomeListItemMsg("2015-1-1,7:30", "0人", "中山公园", "张江高科", 121.419045, 31.221631, 121.587687, 31.201832);
		HomeListItemMsg i2 = new HomeListItemMsg("2015-1-2,7:50", "5人", "人民广场", "上海火车站", 121.475188,31.228833, 121.455211, 31.248774);
		HomeListItemMsg i3 = new HomeListItemMsg("2015-1-1,14:40", "15人", "静安寺", "南京路", 121.445314, 31.223493, 121.479567, 31.233947);		
		mdata.add(i1);
		mdata.add(i2);
		mdata.add(i3);
		return mdata;
	}
	
		
	
	private class mBaseAdapter extends BaseAdapter {
		
		/**
		 * inflate,把layout实例为view对象
		 */
		private LayoutInflater mInflater;
		
		public mBaseAdapter(Context context) {
			this.mInflater = LayoutInflater.from(context);
		}

		@Override
		public int getCount() {
			return mData.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder = null;
			if (convertView == null) {

				holder = new ViewHolder();

				convertView = mInflater.inflate(R.layout.main_tab_home_listview_item, null);
				holder.time				 = (TextView) convertView.findViewById(R.id.listview_item_time);
				holder.num_of_people	 = (TextView) convertView.findViewById(R.id.listview_item_num_of_people);
				holder.startplace		 = (TextView) convertView.findViewById(R.id.listview_item_startplace);
				holder.endplace			 = (TextView) convertView.findViewById(R.id.listview_item_endplace);
				convertView.setTag(holder);

			} else {

				holder = (ViewHolder) convertView.getTag();
			}

			holder.time.setText(mData.get(position).getsTime());
			holder.num_of_people.setText(mData.get(position).getsNum());
			holder.startplace.setText(mData.get(position).getsStartPlace());
			holder.endplace.setText(mData.get(position).getsEndPlace());

			return convertView;
		} 
		
	}
	

}
